package part1.tw;

/**
 * @Author: shaochong
 * @Date: 2021/8/5
 * @Description:
 */
public class Solution {
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = null;
        ListNode tail = null;
        int sub = 0;
        while(l1 != null || l2 != null || sub != 0) {
            int v1 = l1 == null ? 0 : l1.val;
            int v2 = l2 == null ? 0 : l2.val;

            int sum =  v1 + v2 + sub;
            int c1 = sum % 10;
            sub = sum / 10;

            ListNode node = new ListNode(c1, null);
            if (tail == null) {
                tail = node;
                head = node;
            } else {
                tail.next = node;
                tail = node;
            }
            if (l1 !=null) {
                l1 = l1.next;
            }
            if (l2 !=null) {
                l2 = l2.next;
            }
        }
        return head;
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(2, null);
        ListNode l2 = new ListNode(4, null);
        ListNode l3 = new ListNode(9, null);

        ListNode l4 = new ListNode(5, null);
        ListNode l5 = new ListNode(6, null);
        ListNode l6 = new ListNode(4, null);
        ListNode l7 = new ListNode(9, null);

        l1.next = l2;
        l2.next = l3;

        l4.next = l5;
        l5.next = l6;
        l6.next = l7;

        ListNode ans = addTwoNumbers(l1, l4);
        print(ans);
    }

    public static void print(ListNode head) {
        while (head != null) {
            System.out.print(head.val);
            head = head.next;
        }
    }
}
